import os
import nirvanix
import nirvanixutils
from nirvanix import Nirvanix
from nirvanix import Session

from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
import wsgiref.handlers

appkey = 'YOURAPPKEY'
username = 'YOURUSERNAME'
password = 'YOURPASSWORD'

class MainPage(webapp.RequestHandler):
    def get(self):
        path = self.request.get('path')
        parentpath = '/'
        if ((path == None) | (path == '')):
            path = '/'
        else:
            parentpath=os.sep.join(path.split(os.sep)[:-1])

        try:
            session = Session(appkey, username, password)
        except nirvanixutils.NirvanixException, e:
            if e.code == 80001:
                self.response.out.write("Login Failed, Please correct the username and password you provided and try again.")
                return
            else:
                self.response.out.write("The following error occured while logging in: " + e.message)
                return
        maxentries = 500
        imfs = Nirvanix('IMFS', session);
        options = {'folderPath':path,'pageNumber':'1','pageSize':str(maxentries)}
        try:
            doc = imfs.ListFolder(options,False)
            folders = self.getFolders(doc)
            files = self.getFiles(doc)

            template_values = {
                'parentpath': parentpath,
                'path': path,
                'folders': folders,
                'files': files
                }

            browsepath = os.path.join(os.path.dirname(__file__), 'browse.template')
            self.response.out.write(template.render(browsepath, template_values))
        except nirvanixutils.NirvanixException, e:
            self.response.out.write(e)
            self.response.out.write(e.code)

    def getFolders(self, doc):
        folders = []
        for folder in doc.getElementsByTagName("Folder"):
            path = '/' + folder.getElementsByTagName('Path')[0].childNodes[0].nodeValue
            name = folder.getElementsByTagName('Name')[0].childNodes[0].nodeValue
            folders.append({"path":path,"name":name})
        return folders

    def getFiles(self, doc):
        files = []
        for file in doc.getElementsByTagName("File"):
            path = '/' + file.getElementsByTagName('Path')[0].childNodes[0].nodeValue
            name = file.getElementsByTagName('Name')[0].childNodes[0].nodeValue
            files.append({"path":path,"name":name})
        return files

def main():    
    application = webapp.WSGIApplication([('/', MainPage)],debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
    main()
    

